/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author treiman
 */
/*
 * java.io.* for File.
 */
import java.io.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

public class InitClients {
    /*
     * Synchronization variables.
     */
    static CyclicBarrier barrier;
    static CyclicBarrier msgBarrier;
    static CountDownLatch printCd;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        File configFile = null;
        File inputFile = null;
        FileReader fr = null;
        int lineCount = -1;
        if (args.length < 3) {
            System.out.println("Invalid arguments.");
            System.exit(2);
        }
        try {
            /*
             * Open the files. Replace current string values
             * with command line arguments.
             */
            //configFile = new File("config.txt");
            //inputFile = new File("input_vector.txt");
            configFile = new File(args[0]);
            inputFile = new File(args[2]);
            /*
             * If both files exist, create a new FileReader
             * for counting the lines in config file.
             */
            if (configFile.exists() && inputFile.exists()) {
                fr = new FileReader(configFile);
            }
        }
        catch (FileNotFoundException fe) {
            System.err.println("A file could not be opened.");
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        /*
         * Do this only if both files exist.
         */
        if (fr != null) {
            LineNumberReader ln = new LineNumberReader(fr);
            lineCount = 0;
            /*
             * Count the lines in the file.
             */
            try {
                while (ln.readLine() != null) {
                    lineCount++;
                }
                /*
                 * Initialize synchronization variables.
                 */
                barrier = new CyclicBarrier(lineCount);
                msgBarrier = new CyclicBarrier(2);
                printCd = new CountDownLatch(lineCount);
                ln.close();
                fr.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        else {
            System.out.println("Debug!");
        }

        /*
         * If the lineCount is correct, start the same amount of
         * threads and run them.
         * @param
         * - File configFile
         * - int i (line number for the thread)
         * - File inputFile
         * - int lineCount (to avoid recounting in threads)
         */
        if (lineCount >= 0) {
            for (int i = 0; i < lineCount; i++) {
                new Thread(new VectorClockClient(configFile, i, inputFile, lineCount)).start();
            }
        }
    }

}
